package io.sage.controller;


import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.sage.common.utils.CertVerifyUtils;
import io.sage.common.utils.CheckPhone;
import io.sage.common.utils.R;
import io.sage.common.validator.ValidatorUtils;
import io.sage.form.RegisterForm;
import io.sage.modules.employer.entity.Employer;
import io.sage.modules.employer.service.EmployerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 注册接口
 */
@RestController
@RequestMapping("/api")
@Api(tags="注册接口")
public class ApiRegisterController {
    @Autowired
    private EmployerService studentService;

    @PostMapping("register")
    @ApiOperation("注册")
    public R register(@RequestBody RegisterForm form , HttpServletRequest request){
        //表单校验
        ValidatorUtils.validateEntity(form);
        
        boolean idNumber = CertVerifyUtils.isIdNumber(form.getIdcards());
		
		if(!idNumber){
			
			return R.error("身份证不合法");
			
		}
		
		boolean phoneNum = CheckPhone.isPhoneNum(form.getPhone());
		
		if(!phoneNum){
			
			return R.error("手机号不合法");
			
		}
        
        Employer student1;
        
        student1 = studentService.selectByUserName(form.getUsername());
    	if(student1!=null){
    		return R.error("用户名已经存在");
    	}
    	
    	student1 = studentService.selectByIDCard(form.getIdcards());
    	if(student1!=null){
    		return R.error("身份证已经存在");
    	}
    	
    	student1 = studentService.selectByPhone(form.getPhone());
    	if(student1!=null){
    		return R.error("手机号已经存在");
    	}
    	
    	String randomCode = (String) request.getSession().getAttribute("randomCode");
		
		if(randomCode==null||!randomCode.equals(form.getCheckCode())){
            //短信验证码错误
            return R.error("验证码错误");
        }
		
        Employer student = new Employer();
        student.setUserName(form.getUsername());
        student.setUserPwd(DigestUtils.sha256Hex(form.getPassword()));
        
        student.setCreateTime(new Date());
        student.setDeptId(Integer.parseInt(form.getDeptId()));
        student.setEmployeeDeptId(Integer.parseInt(form.getDeptId()));
        student.setDeptNumber(form.getDeptNumber());
        student.setName(form.getName());
        student.setPhone(form.getPhone());
        student.setIDCard(form.getIdcards());
        
        int insert = studentService.insert(student);
        
        if(insert>0){
        	return R.ok();
        }

        return R.error();
    }
}
